var crypto = require('crypto'),
    Acl = require('../acl.js'),
    User = require('../models/user.js'),
    Post = require('../models/post.js');

module.exports = function(app) {
  app.get('/post', Acl.checkLogin);
  app.get('/post', function (req, res) {
    res.render('post/form', {
      title: 'Post',
      post: new Post(req.session.user, '', ''),
      user: req.session.user,
      success: req.flash('success').toString(),
      error: req.flash('error').toString()
    });
  });

  app.post('/post', Acl.checkLogin);
  app.post('/post', function (req, res) {
    var title = req.body.title;
    var content = req.body.content;

    if (!title) {
      req.flash('error', 'Title can\'t be empty!'); 
      return res.redirect('/post');
    }

    if (!content) {
      req.flash('error', 'Content can\'t be empty!'); 
      return res.redirect('/post');
    }

    var currentUser = req.session.user;
    var post = new Post(currentUser.userName, title, content);
    post.save(function (err) {
      if (err) {
        req.flash('error', err); 
        return res.redirect('/');
      }
      req.flash('success', 'Post successfully!');
      res.redirect('/');
    });
  });

  app.get('/post/:id', function (req, res) {
    Post.getOne(req.params.id, function (err, post) {
      if (err) {
        req.flash('error', err); 
        return res.redirect('/');
      }
      res.render('post/view', {
        title: post.title,
        post: post,
        user: req.session.user,
        success: req.flash('success').toString(),
        error: req.flash('error').toString()
      });
    });
  });

  app.get('/post/u/:id', Acl.checkLogin);
  app.get('/post/u/:id', function(req, res) {
    var currentUser = req.session.user;
    Post.getOneForEdit(req.params.id, function (err, post) {
      if (err) {
        req.flash('error', err); 
        return res.redirect('back');
      }
      res.render('post/form', {
        title: 'Edit Post',
        post: post,
        user: req.session.user,
        success: req.flash('success').toString(),
        error: req.flash('error').toString()
      });
    });
  });

  app.post('/post/u/:id', Acl.checkLogin);
  app.post('/post/u/:id', function(req, res) {
    var currentUser = req.session.user;
    var newPost = {id : req.params.id, title : req.body.title, content : req.body.content};
    Post.update(newPost, currentUser, function (err, post) {
      var url = '/post/' + req.params.id;
      if (err) {
        req.flash('error', err); 
        return res.redirect(url);
      }
      req.flash('success', 'Post updated successfully!');
      res.redirect(url);
    });
  });

  app.get('/post/d/:id', Acl.checkLogin);
  app.get('/post/d/:id', function(req, res) {
    Post.delete(req.params.id, function (err, post) {
      if (err) {
        req.flash('error', err);
        return res.redirect('back');
      }
      req.flash('success', 'Post deleted successfully!');
      res.redirect('/');
    });
  });  
};